package Server.controller;

import Plug.operLog.OperLog;
import Plug.result.RetResponse;
import Plug.result.RetResult;
import Server.dao.*;
import Server.entity.InviteUsers;
import Server.entity.Role;
import Server.entity.Users;
import Server.entity.UsersCity;
import Server.service.RedisService;
import Server.tool.BeanToJson;
import Server.tool.CodeUtils;
import Server.tool.EDcrypionUtils;
import Server.tool.HttpRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;

@RestController
@RequestMapping("UserController")
public class UserController {
    @Autowired
    private UsersDao usersDao;
    @Autowired
    private InviteUsersDao inviteUsersDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private CityDao cityDao;
    @Autowired
    private UsersCityDao usersCityDao;
    @Autowired
    private RedisService redisService;
    @Autowired
    private HttpServletRequest request;

    @OperLog("用户更新资料")
    @RequestMapping("UpdateUser")
    public RetResult UpdateUser(@RequestBody Users users){
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        if(!StringUtils.isEmpty(users.getPassword())){
            fspuser.setPassword(new Md5Hash(users.getPassword(), EDcrypionUtils.key, EDcrypionUtils.nbm).toString());
        }
        try {
            fspuser.setName(users.getName());
            fspuser.setIcon(users.getIcon());
            usersDao.save(fspuser);
            usersDao.flush();
            SecurityUtils.getSubject().getSession().setAttribute("Users", fspuser);

            return RetResponse.makeOKRsp();
        }catch (Exception e){
            return RetResponse.makeErrRsp("用户名或昵称或手机或邮箱已存在");
        }
    }

    @RequestMapping("List")
    public RetResult List(@RequestBody JSONObject jsonObject){
        Users entity = (Users) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), Users.class);
        int page = Integer.parseInt(jsonObject.getString("page"))-1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        //管理员-全部
        //业务员-自己的用户
        fspuser=usersDao.findByUuid(fspuser.getUuid());

        if(fspuser.getType().equals(Users.Type.BUSINESS)){
            InviteUsers inviteUsers = new InviteUsers();
            inviteUsers.setUsers(fspuser);
            Users use = new Users();
            use.setName(entity.getName());
            inviteUsers.setInviteUser(use);
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("inviteUser.name", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("inviteUser.mobile", ExampleMatcher.GenericPropertyMatchers.contains());
            Example<InviteUsers> example = Example.of(inviteUsers,matcher);
            Pageable pageable = PageRequest.of(page, size);
            Page<InviteUsers> userlist = inviteUsersDao.findAll(example,pageable);
            List<Users> usersList = new LinkedList<>();
            for(InviteUsers us:userlist.getContent()){
                usersList.add(us.getInviteUser());
            }
            return RetResponse.makeRsp(0, "成功", usersList, (int) userlist.getTotalElements());
        }else {
            Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modifiedTime");
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("mobile", ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Users> example = Example.of(entity,matcher);
            Page<Users> userlist = usersDao.findAll(example,pageable);
            return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int)userlist.getTotalElements());

        }

    }

    @OperLog("用户启用禁用")
    @RequestMapping("Bind")
    public RetResult Bind(@RequestBody Users users){
        users = usersDao.findByUuid(users.getUuid());
        if(users.getStatus().equals(Users.Status.NO)){
            users.setStatus(Users.Status.YES);
        }else{
            users.setStatus(Users.Status.NO);
        }
        usersDao.save(users);
        return RetResponse.makeOKRsp();
    }

    @OperLog("用户注册")
    @RequestMapping("Regist")
    public RetResult Regist(@RequestBody Users users){
        try {
            String code =  redisService.get(users.getMobile());
            if(StringUtils.isEmpty(code)){
                return RetResponse.makeErrRsp("您没有发送验证码");
            }
            if(!code.equals(users.getEmail())){
                return RetResponse.makeErrRsp("验证码不正确，请重新输入");
            }
            users.setIcon("./depot/admin.png");
            users.setRole(roleDao.findByUuid("3"));
            users.setStatus(Users.Status.YES);
            users.setType(Users.Type.USER);
            if(StringUtils.isEmpty(users.getAddress())){
                return RetResponse.makeErrRsp("城市未选择");
            }
            if(cityDao.findByCityLike("%"+users.getAddress()+"%")==null){
                return RetResponse.makeErrRsp("城市不存在");
            }
            UsersCity usersCity = usersCityDao.findByCity(cityDao.findByCityLike(users.getAddress()));
            if(usersCity==null){
                return RetResponse.makeErrRsp("当前城市业务未开通");
            }
            users.setPassword(EDcrypionUtils.shiroPassword(users.getPassword()));
            users=usersDao.save(users);
            InviteUsers inviteUsers = new InviteUsers();
            inviteUsers.setInviteUser(users);
            inviteUsers.setUsers(usersCity.getUsers());
            inviteUsersDao.save(inviteUsers);
        }catch (Exception e){
            return  RetResponse.makeErrRsp("注册失败！");
        }
        return RetResponse.makeOKRsp();
    }

    @OperLog("短信发送")
    @RequestMapping("openNote")
    public RetResult openNote(@RequestBody JSONObject jsonObject) throws UnsupportedEncodingException {
        String mobile = jsonObject.getString("mobile");
        if(usersDao.findByMobile(mobile)!=null){
            return RetResponse.makeErrRsp("当前号码已注册！");
        }else{
            /*
            *
            * 短信验证码
            *
            * */
            String CorpID = "HFJS010341";// 账户名
            String Pwd = "zm0513@";// 密码
            String Mobile = mobile;
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss");
            String send_time = dateTimeFormatter1.format(now);
            String now_time = dateTimeFormatter2.format(now);
            System.out.println(now_time);

            String code=new CodeUtils().getCode(6);
            String Content = "您正在注册财旺商城。本次验证码为："+code+",切勿泄露给他人!";
            String send_content = URLEncoder.encode(
                    Content.replaceAll("<br/>", " "), "GBK");// 发送内容
            String url ="https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID="
                    + CorpID + "&Pwd=" + Pwd + "&Mobile=" + Mobile + "&Content="
                    + send_content + "&Cell=&SendTime=" + send_time;
            String result =  HttpRequest.sendGet(url);
            if(new BigDecimal(result).compareTo(BigDecimal.ZERO)>0){
                redisService.set(mobile,code,600);
            }else{
                return RetResponse.makeErrRsp("短信发送失败");
            }
            return RetResponse.makeOKRsp("验证码已发送至您的手机，请注意查收。（10分钟有效）");
        }
    }
    @OperLog("短信发送修改密码")
    @RequestMapping("openNoteXG")
    public RetResult openNoteXG(@RequestBody JSONObject jsonObject) throws UnsupportedEncodingException {
        String mobile = jsonObject.getString("mobile");
        if(usersDao.findByMobile(mobile)==null){
            return RetResponse.makeErrRsp("当前号码未注册！");
        }else{
            /*
             *
             * 短信验证码
             *
             * */
            String CorpID = "HFJS010341";// 账户名
            String Pwd = "zm0513@";// 密码
            String Mobile = mobile;
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss");
            String send_time = dateTimeFormatter1.format(now);
            String now_time = dateTimeFormatter2.format(now);
            System.out.println(now_time);

            String code=new CodeUtils().getCode(6);
            String Content = "正在修改登陆密码。本次验证码为:"+code+",切勿泄露给他人!";
            String send_content = URLEncoder.encode(
                    Content.replaceAll("<br/>", " "), "GBK");// 发送内容
            String url ="https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID="
                    + CorpID + "&Pwd=" + Pwd + "&Mobile=" + Mobile + "&Content="
                    + send_content + "&Cell=&SendTime=" + send_time;
            String result =  HttpRequest.sendGet(url);
            if(new BigDecimal(result).compareTo(BigDecimal.ZERO)>0){
                redisService.set(mobile,code,600);
            }else{
                return RetResponse.makeErrRsp("短信发送失败");
            }
            return RetResponse.makeOKRsp("验证码已发送至您的手机，请注意查收。（10分钟有效）");
        }
    }
    @RequestMapping("isLogin")
    public RetResult isLogin(){
        return RetResponse.makeOKRsp();
    }
    @RequestMapping("registYWY")
    public RetResult registYWY(@RequestBody Users users){
        users.setIcon("./depot/admin.png");
        users.setRole(roleDao.findByUuid("2"));
        users.setStatus(Users.Status.YES);
        users.setType(Users.Type.BUSINESS);
        users.setPassword(EDcrypionUtils.shiroPassword(users.getPassword()));
        try {
            usersDao.save(users);
            return RetResponse.makeOKRsp();
        }catch (Exception e){
            return RetResponse.makeErrRsp("手机或姓名或用户名重复");
        }
    }
    @OperLog("用户更新资料mobile")
    @RequestMapping("UpdateUserSalf")
    public RetResult UpdateUserSalf(@RequestBody Users users){
        String code =  redisService.get(users.getMobile());
        if(StringUtils.isEmpty(code)){
            return RetResponse.makeErrRsp("您没有发送验证码");
        }
        if(!code.equals(users.getEmail())){
            return RetResponse.makeErrRsp("验证码不正确，请重新输入");
        }
        Users fspuser = usersDao.findByMobile(users.getMobile());
        if(!StringUtils.isEmpty(users.getPassword())){
            fspuser.setPassword(new Md5Hash(users.getPassword(), EDcrypionUtils.key, EDcrypionUtils.nbm).toString());
        }
        try {
            usersDao.save(fspuser);
            usersDao.flush();
            if(SecurityUtils.getSubject()!=null){
                redisService.deleted(request.getHeader("X-real-ip"));
            }
            return RetResponse.makeOKRsp();
        }catch (Exception e){
            return RetResponse.makeErrRsp("用户名或昵称或手机或邮箱已存在");
        }
    }
    @RequestMapping("loginOutMobile")
    public RetResult loginOutMobile(){
        SecurityUtils.getSubject().logout();
        return RetResponse.makeOKRsp();
    }
    @RequestMapping("GetMITeacher")
    public RetResult GetMITeacher(){
        JSONObject jp = new JSONObject();
        jp.put("mine",JSONObject.fromObject("{\n" +
                "                \"username\": \"财旺管家\"\n" +
                "                ,\"id\": \"-7897\"\n" +
                "                ,\"status\": \"online\"\n" +
                "                ,\"avatar\": \"./depot/admin.png\"\n" +
                "    }"));
        JSONArray jo = new JSONArray();
        JSONObject jk = new JSONObject();
        JSONArray jo1 = new JSONArray();

        JSONObject nk = new JSONObject();
        nk.put("username","财旺管家");
        nk.put("id","1111111");
        nk.put("avatar","./depot/admin.png");
        jo1.add(nk);
        jk.put("groupname","财旺管家");
        jk.put("id","1");
        jk.put("online","2");
        jk.put("list",jo1);
        jo.add(jk);
        jp.put("friend",jo);
        return RetResponse.makeRsp(0,"",jp,0);
    }
    /*public static void main(String[] args) throws UnsupportedEncodingException {
        String CorpID = "HFJS010341";// 账户名
        String Pwd = "zm0513@";// 密码
        String Mobile = "15771929325";
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss");
        String send_time = dateTimeFormatter1.format(now);
        String now_time = dateTimeFormatter2.format(now);
        System.out.println(now_time);

        String code=new CodeUtils().getCode(6);
        String Content = "您正在注册财旺商城。本次验证码为："+code+",切勿泄露给他人!";
        String send_content = URLEncoder.encode(
                Content.replaceAll("<br/>", " "), "GBK");// 发送内容
        String url ="https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID="
                + CorpID + "&Pwd=" + Pwd + "&Mobile=" + Mobile + "&Content="
                + send_content + "&Cell=&SendTime=" + send_time;
        String result =  HttpRequest.sendGet(url);
        System.out.println(result);
    }*/
}
